package com.lagou.rabbitmq.controller;

import com.lagou.rabbitmq.entity.Order;
import com.lagou.rabbitmq.entity.OrderDetail;
import com.lagou.rabbitmq.entity.OrderStatus;
import com.lagou.rabbitmq.utils.Utils;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * 订单控制
 */
@Controller
public class OrderController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发起一个订单
     * @param model
     * @return
     */
    @RequestMapping("/order")
    public String order(Model model) throws ExecutionException, InterruptedException {
        List<OrderDetail> details = new ArrayList<>();
        OrderDetail od = new OrderDetail();
        od.setItemId(Utils.generateItemId());
        od.setItemName("苹果");
        od.setItemPrice(125);
        od.setNum(5);
        details.add(od);

        Order order = new Order();
        order.setUserId(Utils.generateUserId());
        order.setOrderId(Utils.generateOrderId());
        // 设置状态为待支付
        order.setStatus(OrderStatus.TO_BE_PAYED.toString());
        order.setDetails(details);

        CorrelationData correlationData = new CorrelationData();
        rabbitTemplate.convertAndSend("x.order","k.order",order,correlationData);
        // 同步等待，可以设置为异步回调
        CorrelationData.Confirm confirm = correlationData.getFuture().get();
        // 判断发送的消息是否得到broker的确认
        boolean confirmAck = confirm.isAck();
        if (!confirmAck){
            return "failorder";
        }

        // 发送延迟等待消息
        rabbitTemplate.convertAndSend("x.ttl","k.ttl" , order.getOrderId());

        model.addAttribute("orderId" , order.getOrderId());

        return "order";
    }

    @RequestMapping("/failorder/{orderId}")
    public String failOrder(@PathVariable String orderId , Model model){
        model.addAttribute("orderId",orderId);
        return "fail";
    }

}
